package com.example.webviewtest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.bluetooth.MyBlueToothService;
import com.example.ping.PingService;
import com.zgkxzx.modbus4And.requset.ModbusParam;
import com.zgkxzx.modbus4And.requset.ModbusReq;
import com.zgkxzx.modbus4And.requset.OnRequestBack;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;


public class MainActivity extends BasicAcivity implements CommonInterface {
    private WebView webView;
    private Button btn;
    private Button btnA10;

    private Button btnping;
    private EditText editText;
    private ProgressDialog dialog;

    public static Activity instance;


    private SensorManager sm;
    //需要两个Sensor
    private Sensor aSensor;
    private Sensor mSensor;
    float[] accelerometerValues = new float[3];
    float[] magneticFieldValues = new float[3];
    StringBuilder s = new StringBuilder();
    StringBuilder orientation = new StringBuilder();
    Long oldTime = new Date().getTime();
    Long nowTime = 0L;
    private static final String TAG = "sensor";


    private ModbusTcpClient mModbusTcpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
//        modbusInit("192.168.1.106",502);

        initListener();
        sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        aSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensor = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        sm.registerListener(myListener, aSensor, SensorManager.SENSOR_DELAY_NORMAL);
        sm.registerListener(myListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
//        更新显示数据的方法
        calculateOrientation();
        testDownloadPicture();
        initLocation();
//        checkAndStartService();
//        finish();
    }

    private void checkAndStartService() {
        if (!isServiceRunning(PingService.class)) {
            Intent serviceIntent = new Intent(this, PingService.class);
            startService(serviceIntent);
        }
    }

    private boolean isServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private void modbusInit(String ip, int port) {
        ModbusReq.getInstance().setParam(new ModbusParam()
                        .setHost(ip)
                        .setPort(port)
                        .setEncapsulated(false)
                        .setKeepAlive(true)
                        .setTimeout(2000)
                        .setRetries(0))
                .init(new OnRequestBack<String>() {
                    @Override
                    public void onSuccess(String s) {
                        Log.d(TAG, "onSuccess " + s);
                        Intent i = new Intent("notifyText");
                        i.putExtra("act", "100");
                        i.putExtra("status", true);
                        i.putExtra("Message", "连接成功");
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
                        readHoldingRegisters(1, 41024, 72);
                    }

                    @Override
                    public void onFailed(String msg) {
                        Log.d(TAG, "onFailed " + msg);
                        Intent i = new Intent("notifyText");

                        i.putExtra("act", "0");
                        i.putExtra("status", false);
                        i.putExtra("Message", "连接失败");
                        LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
                    }
                });
    }

    public void readCoil(int slaveid, int start, int len) {//读单个线圈
        ModbusReq.getInstance().readCoil(new OnRequestBack<boolean[]>() {
            @Override
            public void onSuccess(boolean[] booleen) {
                Log.d(TAG, "readCoil onSuccess " + Arrays.toString(booleen));
                Intent i = new Intent("notifyText");
                i.putExtra("act", "1");
                i.putExtra("status", true);
                i.putExtra("Message", Arrays.toString(booleen));
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "readCoil onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "1");
                i.putExtra("status", false);
                i.putExtra("Message", "读取线圈失败");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, len);
    }


    public void readDiscreteInput(int slaveid, int start, int len) {//读离散输入

        ModbusReq.getInstance().readDiscreteInput(new OnRequestBack<boolean[]>() {
            @Override
            public void onSuccess(boolean[] booleen) {
                Log.d(TAG, "readDiscreteInput onSuccess " + Arrays.toString(booleen));
                Intent i = new Intent("notifyText");
                i.putExtra("act", "2");
                i.putExtra("status", true);
                i.putExtra("Message", Arrays.toString(booleen));
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "readDiscreteInput onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "2");
                i.putExtra("status", false);
                i.putExtra("Message", "读取线圈失败");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, len);
    }

    public void readHoldingRegisters(int slaveid, int start, int len) {//读保持寄存器
        //readHoldingRegisters
        ModbusReq.getInstance().readHoldingRegisters(new OnRequestBack<short[]>() {
            @Override
            public void onSuccess(short[] data) {
                Log.d(TAG, "readHoldingRegisters onSuccess " + Arrays.toString(data));
                Intent i = new Intent("notifyText");
                i.putExtra("act", "3");
                i.putExtra("status", true);
                i.putExtra("Message", Arrays.toString(data));
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "readHoldingRegisters onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "3");
                i.putExtra("status", false);
                i.putExtra("Message", "读取线圈失败");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, len);
    }

    public void readInputRegisters(int slaveid, int start, int len) {//读输入寄存器
        ModbusReq.getInstance().readInputRegisters(new OnRequestBack<short[]>() {
            @Override
            public void onSuccess(short[] data) {
                Log.d(TAG, "readInputRegisters onSuccess " + Arrays.toString(data));
                Intent i = new Intent("notifyText");
                i.putExtra("act", "4");
                i.putExtra("status", true);
                i.putExtra("Message", Arrays.toString(data));
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "readInputRegisters onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "4");
                i.putExtra("status", false);
                i.putExtra("Message", "读取线圈失败");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, len);
    }

    public void writeCoil(int slaveid, int start, boolean value) {//写单个线圈
        ModbusReq.getInstance().writeCoil(new OnRequestBack<String>() {
            @Override
            public void onSuccess(String s) {
                Log.e(TAG, "writeCoil onSuccess " + s);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "writeCoil onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "5");
                i.putExtra("status", false);
                i.putExtra("Message", "msg");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, value);
    }

    public void writeRegister(int slaveid, int start, int value) {//写寄存器
        ModbusReq.getInstance().writeRegister(new OnRequestBack<String>() {
            @Override
            public void onSuccess(String s) {
                Log.e(TAG, "writeRegister onSuccess " + s);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "writeRegister onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "6");
                i.putExtra("status", false);
                i.putExtra("Message", "msg");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, value);
    }

    public void writeRegisters(int slaveid, int start, short[] value) {//写多个寄存器
        ModbusReq.getInstance().writeRegisters(new OnRequestBack<String>() {
            @Override
            public void onSuccess(String s) {
                Log.e(TAG, "writeRegisters onSuccess " + s);
            }

            @Override
            public void onFailed(String msg) {
                Log.e(TAG, "writeRegisters onFailed " + msg);
                Intent i = new Intent("notifyText");
                i.putExtra("act", "16");
                i.putExtra("status", false);
                i.putExtra("Message", "msg");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            }
        }, slaveid, start, value);
    }


    LocationManager manager;

    /**
     * 初始化定位管理,android自带卫星
     */
    private void initLocation() {
        manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> allProviders = manager.getAllProviders();
        //判断GPS是否正常启动
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(this, "请开启GPS导航", Toast.LENGTH_SHORT).show();
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            try {
                ((Activity) getApplicationContext()).startActivityForResult(intent, 0);
            } catch (Exception e) {

            }
            return;
        }
        //添加卫星状态改变监听
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            manager.registerGnssStatusCallback(new LocaCallback());
        }
        //1000位最小的时间间隔，1为最小位移变化；也就是说每隔1000ms会回调一次位置信息
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
//                Toast.makeText(MainActivity.this, "onLocationChanged: "+"经度："+location.getLongitude()+"，纬度："+location.getLatitude(), Toast.LENGTH_SHORT).show();
                Log.d("TAG", "onLocationChanged: " + "经度：" + location.getLongitude() + "，纬度：" + location.getLatitude());
//                Toast.makeText(KeepAliveService.this, "经度："+location.getLongitude()+"，纬度："+location.getLatitude(), Toast.LENGTH_SHORT).show();

                Toast.makeText(MainActivity.this, "经度：" + location.getLongitude() + "纬度：" + location.getLatitude(), Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    public class LocaCallback extends GnssStatus.Callback {
        @Override
        public void onSatelliteStatusChanged(GnssStatus status) {
            super.onSatelliteStatusChanged(status);
            int satelliteCount = status.getSatelliteCount();
            //解析组装卫星信息
            makeGnssStatus(status, satelliteCount);
        }

        @Override
        public void onStarted() {
            super.onStarted();
        }

        @Override
        public void onStopped() {
            super.onStopped();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void makeGnssStatus(GnssStatus status, int satelliteCount) {
        //当前可以获取到的卫星总数，然后遍历
        if (satelliteCount > 0) {
            for (int i = 0; i < satelliteCount; i++) {
                //GnssStatus的大部分方法参数传入的就是卫星数量的角标
                //获取卫星类型
                int type = status.getConstellationType(i);
                if (GnssStatus.CONSTELLATION_BEIDOU == type) {
                    //北斗卫星类型的判断
                }
            }
        }
    }

    private void testDownloadPicture() {
        new Thread(new Runnable() {
            @Override
            public void run() {
//                SaveUtils.saveImgFileToAlbum(MainActivity.this, "http://10.19.30.10:8008/rds/media/other/2024/6/14/1718352396854.jpg");
                /*//加载网络图片
                InputStream inputStream = MyDwImgUtils.getImageStream("http://10.19.30.10:8008/rds/media/other/2024/6/14/1718352396854.jpg");
                //设置保存的图片名称
                String displayName = System.currentTimeMillis()+".jpg";
                //设置保存的图片类型
                String mimeType = "image/jpeg";
                Bitmap.CompressFormat compressFormat = Bitmap.CompressFormat.JPEG;
                String uri1 = MyDwImgUtils.addInputStreamToAlbum(MainActivity.this, inputStream, displayName, mimeType, compressFormat);*/
            }
        }).start();
    }


    @Override
    protected void onResume() {
        super.onResume();
        sm.registerListener(myListener, aSensor, SensorManager.SENSOR_DELAY_NORMAL);
        sm.registerListener(myListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        int flags = getWindow().getAttributes().flags;
        boolean isFlagSecure = (flags & WindowManager.LayoutParams.FLAG_SECURE) != 0;
        Log.d("FLAG_SECURE", "是否生效: " + isFlagSecure); // 输出true表示生效
    }

    @Override
    public void onPause() {
        sm.unregisterListener(myListener);
        super.onPause();
    }

    final SensorEventListener myListener = new SensorEventListener() {
        public void onSensorChanged(SensorEvent sensorEvent) {
            if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
                magneticFieldValues = sensorEvent.values;
            if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
                accelerometerValues = sensorEvent.values;
            calculateOrientation();
        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    };


    private void calculateOrientation() {
        float[] values = new float[3];
        float[] R = new float[9];
        SensorManager.getRotationMatrix(R, null, accelerometerValues, magneticFieldValues);
        SensorManager.getOrientation(R, values);
        // 要经过一次数据格式的转换，转换为度
        values[0] = (float) Math.toDegrees(values[0]);
        nowTime = new Date().getTime();
        s.setLength(0);
        orientation.setLength(0);
        if (values[0] >= -5 && values[0] < 5) {
            orientation.append("正北");
        } else if (values[0] >= 5 && values[0] < 85) {
            orientation.append("东北");
        } else if (values[0] >= 85 && values[0] <= 95) {
            orientation.append("正东");
        } else if (values[0] >= 95 && values[0] < 175) {
            orientation.append("东南");
        } else if ((values[0] >= 175 && values[0] <= 180) || (values[0]) >= -180 && values[0] < -175) {
            orientation.append("正南");
        } else if (values[0] >= -175 && values[0] < -95) {
            orientation.append("西南");
        } else if (values[0] >= -95 && values[0] < -85) {
            orientation.append("正西");
        } else if (values[0] >= -85 && values[0] < -5) {
            orientation.append("西北");
        }
        s.append(orientation);
        s.append(Math.round(values[0]) < 0 ? Math.round(values[0]) + 360 : Math.round(values[0]));
        if (nowTime - oldTime >= 1000) {//如果大于1s
            testJS(s.toString());
            oldTime = nowTime;
            System.out.println("当前方位：" + s);
        }
    }

    @Override
    protected void setContentView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,WindowManager.LayoutParams.FLAG_SECURE);
        setContentView(R.layout.activity_main);
    }

    private Button btnOppo;
    @Override
    protected void initView() {
        webView = findViewById(R.id.webview);
        //浏览器调试功能
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        btn = findViewById(R.id.btn);
        btnA10 = findViewById(R.id.A10);
        btnping = findViewById(R.id.ping);
        editText = findViewById(R.id.edit_text);
        btnOppo = findViewById(R.id.btnOppo);
        WebSettings webSettings = webView.getSettings();
        //设置是否启动javascript
        webSettings.setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            // newProgress是1-100之间的整数
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                // 网页加载完成
                if (newProgress == 100) {
                    // 关闭加载完毕，关闭ProgressDialog
                    closeDialog();
                } else {
                    // 网页正在加载,打开ProgressDialog
                    openDialog(newProgress);
                }
            }

            /**
             * 支持alert效果
             */
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                //此处可以弹出dialog
                return true;
            }

            /**
             * 处理Js的Confirm
             */
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                //此处可以弹出警告弹框
                return true;
            }

            private void openDialog(int newProgress) {
                if (dialog == null) {
                    dialog = new ProgressDialog(MainActivity.this);
                    dialog.setTitle("正在加载");
                    dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    dialog.setProgress(newProgress);
                    dialog.show();
                } else {
                    dialog.setProgress(newProgress);
                }

            }

            protected void closeDialog() {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                    dialog = null;
                }
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求(即新的请求地址)，均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (url.toString().contains("sina.cn")) {
                    view.loadUrl("http://ask.csdn.net/questions/178242");
                    return true;
                }
                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求(即新的请求地址)，均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.getUrl().toString().contains("sina.cn")) {
                        view.loadUrl("http://ask.csdn.net/questions/178242");
                        return true;
                    }
                }
                return false;
            }
        });

    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sm.unregisterListener(myListener);
        stopService(new Intent(this, MyBlueToothService.class));
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void testJS(String s) {
        editText.setText("");
        webView.loadUrl("javascript:test(" + "'" + s + "'" + ")");
        System.out.println("javascript:test(" + "'" + s + "'" + ")");
    }

    @Override
    protected void initEvent() {
        startService(new Intent(this, MyBlueToothService.class));
        String logPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/battery";
        File file = new File(logPath);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            System.out.println("创建文件夹是否成功"+mkdirs);
        }
        webView.addJavascriptInterface(new JsFunction(MainActivity.this), "justTest");
        webView.loadUrl("file:///android_asset/test.html");
//        webView.loadUrl("https://zhuanlan.zhihu.com/p/451291388");
    }

    @Override
    public void initListener() {
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                testJS(editText.getText().toString());
                Intent intent = new Intent(MainActivity.this, TestA18Activity.class);
                startActivity(intent);
            }
        });
        btnA10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, TestA10Activity.class);
                startActivity(intent);
            }
        });
        editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    testJS(editText.getText().toString());
                    return true;
                }
                return false;
            }
        });
        btnping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, PingActivity.class);
                startActivity(intent);
            }
        });
        btnOppo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, TestOppoActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //判断网页是否能返回
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            } else {
                System.exit(0);
            }
        }
        return super.onKeyDown(keyCode, event);
    }


}